package edu.cuit.avatar.concurrent;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/17 14:51
 */
public class Racer implements Runnable{
    private String victor;
    @Override
    public void run() {
        for(var steps = 1; steps <= 100; steps++){
            System.out.println(Thread.currentThread().getName() + "跑了：" + steps);
            if("rabbit".equals(Thread.currentThread().getName()) && steps == 20){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            if(gameOver(steps)){
                System.out.println("比赛结束");
                break;
            }
        }
    }

    //比赛是否结束
    public boolean gameOver(int steps){
        if(victor != null) return true;
        if(steps == 100){
            victor = Thread.currentThread().getName();
            System.out.println("胜利者===>" + victor);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        var racer = new Racer();
        new Thread(racer, "rabbit").start();
        new Thread(racer, "tortoise").start();
    }
}
